package cat.joronya.supermanager.home;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.SupermanagerPreferenceActivity;
import cat.joronya.supermanager.service.SupermanagerServiceHelper;

public class HomeFragment extends Fragment 
{
	private final String TAG = "supermanager";
	private Cursor cursor = null;
	private HomeObserver homeObserver = null;
	private SimpleDateFormat simpleDateFormat= null;
	
	private OnAboutListener mAboutListener;
	
	public interface OnAboutListener {
    	public void showAboutDialog();
    }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) 
	{
		View home = inflater.inflate(R.layout.home, null);
		
		simpleDateFormat = new SimpleDateFormat("EEEE d/MM, HH:mm'h'", Locale.getDefault());
        
        // set default values in preferences not setted by user
        PreferenceManager.setDefaultValues(getActivity(),
        		R.xml.preferences, 
        		false);
        
        cursor = getActivity().getContentResolver().query(Supermanager.Home.CONTENT_URI, 
        		Supermanager.Home.PROJECTION, 
           		null,
           		null,
                Supermanager.Home.DEFAULT_SORT_ORDER);
        
        homeObserver = new HomeObserver(new Handler());
        
        getActivity().getContentResolver().registerContentObserver(Supermanager.Home.CONTENT_URI, 
        		false, homeObserver);
        
        // avisem q el fragment te menu pq es cridi
        setHasOptionsMenu(true);
		
		return home;
	}
	
	@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mAboutListener = (OnAboutListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnAboutListener");
        }
    }
	
	/**
     * Update fields.
     */
    private void updateHomeFields()
    {
    	final TextView day = (TextView) getView().findViewById(R.id.home_day);
    	final TextView duetimeLabel = (TextView) getView().findViewById(R.id.home_label);
    	final LinearLayout duetimeRow = (LinearLayout) getView().findViewById(R.id.home_duetime_row);
		final TextView duetime = (TextView) getView().findViewById(R.id.home_duetime);
		final WebView homeInfo = (WebView) getView().findViewById(R.id.home_info);
		final ImageView status = (ImageView) getView().findViewById(R.id.home_status);

		if( cursor.moveToFirst() )
        {   
    		duetimeRow.setVisibility(View.GONE);
			day.setText(getString(R.string.home_day, cursor.getString(1)));
			Timestamp duetimestamp = null;
    		Integer duetimeDay = null;
    		
    		try{
        		int homeStatus = cursor.getInt(2);
        		if( homeStatus == Supermanager.OPEN_STATUS )
        		{        			
        			long timestamp = cursor.getInt(4);
        			duetimestamp = new Timestamp(timestamp*1000);
        			duetimeDay = cursor.getInt(5);
        			Log.d(TAG,"HomeActivity duetimeValue: "+duetimestamp+
        					", getTime(): "+duetimestamp.getTime()+
        					", cursor.getInt(4): "+timestamp);
        		
        			if( duetimestamp != null )
        			{
        				duetimeLabel.setText(getString(R.string.home_label,
        						duetimeDay.toString()));
        				duetime.setText(getString(R.string.home_duetime, 
        						simpleDateFormat.format(duetimestamp.getTime())));
        				duetimeRow.setVisibility(View.VISIBLE);
        			}
        		}
    		}
    		catch(Exception e){
    			Log.d(TAG, "HomeActivity: duetimeValue or duetimeDay are NULL");
    		}
    		
    		homeInfo.loadDataWithBaseURL("http://supermanager.acb.com", cursor.getString(3), "text/html","utf-8", "");
    		switch(Integer.valueOf(cursor.getString(2)))
    		{
    			case Supermanager.CLOSED_STATUS:
    				status.setImageResource(R.drawable.closed);
    				break;
    			case Supermanager.OPEN_NO_CHANGES_STATUS:
    				status.setImageResource(R.drawable.open_changes_closed);
    				break;
    			case Supermanager.OPEN_STATUS:
    				status.setImageResource(R.drawable.open);
    				break;
    			case Supermanager.AUTH_ERROR_STATUS:
    			case Supermanager.OTHER_ERROR_STATUS:
    			case Supermanager.CONNECTIVITY_ERROR_STATUS:
    				status.setImageResource(R.drawable.error);
    				break;
    			default:
    				status.setImageResource(R.drawable.refresh);
    		}
        }
		else
		{
    		day.setText(getString(R.string.home_day, ""));
    		duetime.setText(getString(R.string.home_duetime, ""));
    		homeInfo.loadData(getString(R.string.home_info, ""),"text/html","ISO-8859-1");
    		status.setImageResource(R.drawable.refresh);		
		}
    }
    
    public void openLink(View view) 
	{
    	// throw CONTENT_URI of web
    	Intent i = new Intent(Intent.ACTION_VIEW);
    	i.setData(Uri.parse(getString(R.string.about_link)));
    	startActivity(i);
	}
	
    @Override
    public void onConfigurationChanged(Configuration newConfig) 
    {
    	Log.d(TAG,"HomeActivity.onConfigurationChanged called");
		
		// actualitzem dades
		updateHomeFields();
    	super.onConfigurationChanged(newConfig);
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) 
    {
    	inflater.inflate(R.menu.home, menu);
    	super.onCreateOptionsMenu(menu, inflater);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
    	// Handle item selection
        switch (item.getItemId()) 
        {
        	case R.id.refresh:
				// cridar refresh al REST method
           		SupermanagerServiceHelper.getInstance(getActivity()).fullUpdate(null,true);
				return true;
        	case R.id.settings:
        		// llancem Preferences activity
        		Intent settingsActivity = new Intent(getActivity(),
        				SupermanagerPreferenceActivity.class);
        		startActivity(settingsActivity);
        		return true;
        	case R.id.about:
        		// show about progress
        		mAboutListener.showAboutDialog();
        		return true;
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public void onResume() 
    {
    	// update home fields
    	updateHomeFields();
    	
    	super.onResume();
    }
    
    @Override
    public void onDestroy() 
    {
    	getActivity().getContentResolver().unregisterContentObserver(homeObserver);
    	super.onDestroy();
    }
    
	/**
     * Observer to register Home content and keep updated
     * HomeActivity content.
     * @author pol
     *
     */
    class HomeObserver extends ContentObserver
    {
		public HomeObserver(Handler handler) 
		{
			super(handler);
		}
    	
		@Override
		public boolean deliverSelfNotifications() 
		{
			return false;
		}

		@Override
		public void onChange(boolean selfChange) 
		{
			super.onChange(selfChange);
			updateHomeFields();
		}
    }
}
